/*
 * Copyright (C) 2010 The MobileSecurePay Project
 * All right reserved.
 * author: shiqun.shi@alipay.com
 */

package com.skytech.chatim.sky.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * @author czq 网络连接工具类
 * 
 */
public class NetworkHelper {
    static final String TAG = NetworkHelper.class.getSimpleName();
   
    private int connectTimeout = 30 * 1000;
    private int readTimeout = 30 * 1000;
    Proxy mProxy = null;
    Context mContext;

    public NetworkHelper(Context context) {
        this.mContext = context;
        setDefaultHostnameVerifier();
    }

    /**
     * 检查代理，是否cnwap接入
     */
    private void detectProxy() {
        ConnectivityManager cm = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.isAvailable()
                && ni.getType() == ConnectivityManager.TYPE_MOBILE) {
            String proxyHost = android.net.Proxy.getDefaultHost();
            int port = android.net.Proxy.getDefaultPort();
            if (proxyHost != null) {
                final InetSocketAddress sa = new InetSocketAddress(proxyHost,
                        port);
                mProxy = new Proxy(Proxy.Type.HTTP, sa);
            }
        }
    }

    private void setDefaultHostnameVerifier() {
        //
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }

    public static String getHttpResponse(Context context, String strUrl) {
        NetworkHelper networkHelper = new NetworkHelper(context);
        HttpPost httpRequest = new HttpPost(strUrl);
        return networkHelper.SendAndWaitResponse(httpRequest);

    }

    public static String getHttpResponse(Activity activity,
            AppServerRequest request) {
        NetworkHelper networkHelper = new NetworkHelper(activity);
        HttpUriRequest httpRequest = RestRequestUtil.getHttpReqeust(request);
        return networkHelper.SendAndWaitResponse(httpRequest);
    }

    /**
     * 发送和接收数据
     * 
     * @param strReqData
     *            请求数据
     * @param strUrl
     *            请求地址
     * @return
     */
    private String SendAndWaitResponse(HttpUriRequest httpRequest) {
        Log.d(TAG, "http request " + httpRequest.getURI());
        //
        detectProxy();
        String strResponse = null;
        try {

            HttpClient httpclient = new DefaultHttpClient();
            // 取得HttpResponse
            HttpResponse httpResponse = httpclient.execute(httpRequest);
            // HttpStatus.SC_OK表示连接成功
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 取得返回的字符串
                strResponse = EntityUtils.toString(httpResponse.getEntity());
                // mTextView.setText(strResult);
            } else {
                // mTextView.setText("请求错误!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return strResponse;
    }

    /**
     * 流转字符串方法
     * 
     * @param is
     * @return
     */
    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static void getHttpResponse(Activity activity, String url,
            Handler handler, int messageID) {
        String text = getHttpResponse(activity, url);
        if (handler == null) {
            return;
        }
        Message message = handler.obtainMessage(messageID);
        message.obj = text;
        handler.sendMessage(message);
    }

    public static void sendNetRequestInOtherThread(final Activity activity,
            final String url, final Handler handler, final int messageID) {
        new Thread() {

            @Override
            public void run() {
                NetworkHelper
                        .getHttpResponse(activity, url, handler, messageID);
            }

        }.start();

    }

    public static void sendNetRequestInOtherThread(final Activity activity,
            final String url) {
        sendNetRequestInOtherThread(activity, url, null, 0);
    }

}
